package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"time"
)

func main() {
	// 定义命令行标志
	ip := flag.String("ip", "localhost:3306", "target ip")
	port := flag.String("port", "3307", "port")
	managerIp := flag.String("gui", "3308", "gui port")

	flag.Parse()

	// 设置默认时区为北京时间
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		log.Fatal("无法加载时区:", err)
	}
	time.Local = loc

	listener, err := net.Listen("tcp", ":"+*port)
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()

	// 监听MySQL连接
	go func() {
		for {
			clientConn, err := listener.Accept()
			if err != nil {
				log.Println("Error accepting connection:", err)
				continue
			}
			go handleConnection(clientConn, *ip)
		}
	}()

	fmt.Printf("server is on %s\n", *port)
	fmt.Printf("manager is on %s\n", *managerIp)

	// 管理端
	startManager(*managerIp)
}

func handleConnection(clientConn net.Conn, ip string) {
	defer clientConn.Close()

	mysqlConn, err := net.Dial("tcp", ip)
	if err != nil {
		log.Println("连接到MySQL时出错:", err)
		return
	}
	defer mysqlConn.Close()

	// go io.Copy(mysqlConn, clientConn)
	// go io.Copy(clientConn, mysqlConn)

	// var wg sync.WaitGroup
	// wg.Add(1)
	// wg.Wait()

	// 使用监视的读写器包装连接
	monitoredConn := newMonitoredConnection()
	defer monitoredConn.Close()

	monitoredClientConn := struct {
		io.Reader
		io.Writer
	}{
		Reader: newMonitoredReader(clientConn, "客户端到代理", monitoredConn),
		Writer: newMonitoredWriter(clientConn, "代理到客户端", monitoredConn),
	}

	monitoredMysqlConn := struct {
		io.Reader
		io.Writer
	}{
		Reader: newMonitoredReader(mysqlConn, "MySQL到代理", monitoredConn),
		Writer: newMonitoredWriter(mysqlConn, "代理到MySQL", monitoredConn),
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		_, _ = io.Copy(monitoredClientConn, monitoredMysqlConn)
		cancel()
	}()
	go func() {
		_, _ = io.Copy(monitoredMysqlConn, monitoredClientConn)
		cancel()
	}()

	<-ctx.Done()
}
